<template>
  <section>
    <el-col :sm="24" :lg="16">
      <div class="grid-content bg-purple">
        <div class="dev-title">添加设备模板</div>
      </div>
      <div class="col-bg clearfix">
        <el-form
          ref="form"
          :rules="addFormRules"
          :model="form"
          label-width="120px"
          @submit.prevent="onSubmit"
          style="padding: 15px;margin:20px auto 10px;max-width: 900px;"
        >
          <el-form-item label="设备模板名称" class="grade" prop="name">
            <el-input v-model="form.name"></el-input> 
          </el-form-item>
          <!-- <el-form-item label="终端用户" class="grade" prop="terminalUser">
            <el-select v-model="form.terminalUser" placeholder="终端用户">
              <el-option v-for="item in terminal_list" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="设备分组" class="grade" prop="deviceGroupId">
                            <el-select v-model="form.deviceGroupId" placeholder="请选择活动区域">
                                <el-option v-for="item in grouplist" :label="item.name" :value="item.id"></el-option>
                            </el-select>
          </el-form-item>-->
          <el-form-item label="设备类型" class="grade" prop="deviceTypeId">
            <el-select v-model="form.deviceTypeId" placeholder="请选择设备类型">
              <el-option v-for="item in typelist" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="网关型号" class="grade" prop="deviceModelId">
            <el-select v-model="form.deviceModelId" placeholder="请选择网关型号">
              <el-option v-for="item in modellist" :label="item.name" :value="item.modelId"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="设备所属用户" class="grade" prop="deviceUserId">
            <el-select v-model="form.deviceUserId" placeholder="请选择所属用户">
              <el-option v-for="item in userlist" :label="item.name" :value="item.companyId"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="通信协议" prop="protocol">
                            <el-radio-group v-model="form.protocol">
                                <el-radio label="0" checked>Modbus TCP</el-radio>
                            </el-radio-group>
          </el-form-item>-->

          <el-form-item label="移动属性" class="grade" prop="moving">
            <el-radio-group v-model="form.moving">
              <el-radio label="0">静止</el-radio>
              <el-radio label="1">移动</el-radio>
            </el-radio-group> 
          </el-form-item>
          <!-- <el-form-item label="订单名称" class="grade" prop="orderSn">
            <el-select v-model="form.orderSn">
              <el-option v-for="item in orderlist" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="行业" prop="guild" class="grade">
            <!-- <el-input v-model="form.guild"></el-input> -->
            <el-select v-model="form.guild" placeholder="请选择行业">
              <el-option v-for="item in industrylist" :label="item.remark" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item v-if="menubt.indexOf('/template/app')>-1" label="UI模板">
              <el-select v-model="form.uiId" placeholder="UI模板">
                  <el-option v-for="item in templateUIlist" :label="item.name" :value="item.uiId"></el-option>
              </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="排序值" prop="area">
            <el-input type="number" v-model="form.area"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="是否体验设备">
                    <el-radio-group v-model="form.experience">
                        <el-radio label="0">否</el-radio>
                        <el-radio label="1">是</el-radio>
                    </el-radio-group>
          </el-form-item>-->
          <el-form-item label="备注">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-form-item>

          <el-form-item label-position="center">
            <div class="grid-content bg-purple">
              <div class="dev-title">设备地图</div>
            </div>
            <div id="allmap" ref="allmap"></div>
            <div class="map_position clearfix ng-binding">
              <el-input
                type="text"
                id="suggestId"
                name="address_detail"
                placeholder="地址"
                v-model="address_detail"
                class="input_style"
              ></el-input>
              <!-- <div>{{form.deviceLocation.address}}</div> -->
              经度：{{form.deviceLocation.longitude}},纬度：{{form.deviceLocation.latitude}}
            </div>
          </el-form-item>
          <el-form-item label="设备图片">
            <!-- <el-form-item label="排序值" class="grade">
              <el-input v-model="form.devicePictureList[0].priority"></el-input>
            </el-form-item> -->
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader" 
                action="/api/auth/image_file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="fileList"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form-item>
          <el-form-item label="设备从机">
            <el-row
              :gutter="10"
              style="padding:0 10px"
              v-for="(item,index) in  form.deviceSlaveList"
            >
              <!-- <el-col :span="5">
                <el-input v-model="item.priority" auto-complete="off" placeholder="排序值"></el-input>
              </el-col> -->
              <el-col :span="5">
                <el-input v-model="item.name" auto-complete="off" placeholder="从机名称"></el-input>
              </el-col>
              <el-col :span="5">
                <el-input v-model="item.slaveSn" auto-complete="off" placeholder="从机编号"></el-input>
              </el-col>
              <el-col :span="5">
                <el-select v-model="item.deviceDataRecipeId" placeholder="请选择数据模板">
                  <el-option v-for="list in recipelist" :label="list.name" :value="list.id"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <i
                  class="el-icon-delete"
                  @click="deviceSlaveListdel(index)"
                  style="color:red;font-size:20px;line-height:40px;"
                ></i>
              </el-col>
            </el-row>
            <el-button style="position:absolute;right:10%;bottom: 0" @click.native.prevent="deviceSlaveListadd()" type="primary">添加设备从机</el-button>
          </el-form-item>

          <el-form-item>
            <!-- <el-button @click.native.prevent="deviceSlaveListadd()" type="primary">添加设备从机</el-button> -->
            <el-button
              @click.native.prevent="onSubmit()"
              type="primary"
              :loading="addLoading"
            >立即添加设备模板</el-button>
            <!-- <el-button @click.native.prevent>取消</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </el-col>
    <!-- <el-col :sm="24" :lg="8" style="padding-left: 20px">
         
                <div class=" clearfix">
          
                    <el-collapse v-model="activeName" accordion>
                        <el-collapse-item title="设备类型" name="1">
                            <div>暂无</div>
                        </el-collapse-item>
                        <el-collapse-item title="通讯协议" name="2">
                            <div>暂无</div>
                        </el-collapse-item>
                        <el-collapse-item title="从机" name="3">
                            <div>什么是从机？</div>
                            <div>设备是连接东源公投云的串口转网络设备，从机是RS-485总线上的串口设备。</div>
                            <div>什么是序号？</div>
                            <div>在远程采集和控制中，通过设备ID、序号、数据点ID锁定要控制的数据点。</div>
                            <div>例：温度大于40告警；温度到50会触发告警推送并存储告警信息，再次上传“60”不会触发告警且不保存数据。温度到30，会触发恢复告警推送并存储告警消息</div>
                        </el-collapse-item>
                        <el-collapse-item title="通讯密码" name="4">
                            <div>设置默认设备接入的密码，支持密码自定义，实现不同设备接入密码不同。</div>
                            <div>设备一旦接入成功后轻易不要修改，否则会造成设备由于密码错误无法再次接入。-485总线上的串口设备。</div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
    </el-col>-->
  </section>
</template>
    
    <script>
import {
  file_upload,
  device_template_post,
  device_group_query,
  device_type_query,
  device_model_query,
  user_query,
  device_data_recipe_query,
  dict_query,
  terminal_user_query,
  order_query,
  query_device_user,
  template_ui_query,
  device_template_ui_company_query
} from "../../api/api";
export default {
  data() {
    return {
      fileList: {
          token: JSON.parse(localStorage.getItem('key'))
      },
      orderlist: "",
      deviceaddlist: [
        {
          deviceSn: "",
          name: "",
          password: ""
        }
      ],
      industrylist: "",
      userlocation: {
        lng: "",
        lat: ""
      },
      address_detail: null,
      activeName: "1",
      recipelist: "",
      grouplist: [],
      typelist: "",
      modellist: "",
      userlist: "",
      addLoading: false,
      addFormRules: {
        orderSn: [{
            required: true,
            message: '必填',
            trigger: 'blur'
        }],
        deviceSn: [
          {
            required: true,
            message: "网关SN必填",
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            message: "设备模板名称必填",
            trigger: "blur"
          },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        password: [
          {
            required: true,
            message: "设备密码必填",
            trigger: "blur"
          }
        ],
        deviceGroupId: [
          {
            required: true,
            message: "设备分组必填",
            trigger: "blur"
          }
        ],
        deviceTypeId: [
          {
            required: true,
            message: "设备类型必填",
            trigger: "blur"
          }
        ],
        deviceModelId: [
          {
            required: true,
            message: "网关型号必填",
            trigger: "blur"
          }
        ],
        deviceUserId: [
          {
            required: true,
            message: "设备所属用户必填",
            trigger: "blur"
          }
        ],
        protocol: [
          {
            required: true,
            message: "通信协议",
            trigger: "blur"
          }
        ],
        moving: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        guild: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        area: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        priority: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        experience: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        remark: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        terminalUser: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ]
      },
      imageUrl: "",
      form: {
        name: "",
        deviceGroupId: "",
        deviceTypeId: "",
        deviceModelId: "",
        deviceUserId: "",
        protocol: "0",
        moving: "0",
        guild: "",
        area: "",
        priority: "",
        experience: "",
        remark: "",
        terminalUser: "",
        uiId: "",
        deviceLocation: {
          longitude: "",
          latitude: "",
          province: "",
          city: "",
          county: "",
          address: ""
        },
        devicePictureList: [
          {
            priority: "",
            path: ""
          }
        ],
        deviceSlaveList: [
          {
            priority: "",
            name: "",
            slaveSn: "",
            deviceDataRecipeId: ""
          }
        ],
        orderSn: ""
      },
      templateUIlist:[],
      terminal_list: "",
      menubt:''
    };
  },
  created: function() {
    var _this = this;
    document.onkeydown = function(e) {
      let key = window.event.keyCode;
      if (key == 13) {
        _this.onSubmit();
      }
    };
  },

  methods: {
    templateget() {},
    addlistdel(s) {
      this.deviceaddlist.splice(s, 1);
    },
    addlist() {
      this.deviceaddlist.push({
        deviceSn: "",
        name: "",
        password: ""
      });
    },
    map() {
      var th = this;
      let self = this;
      let map = new BMap.Map(this.$refs.allmap);
      // 创建Map实例
      // map.centerAndZoom(new BMap.Point(116.404, 39.915), 5);
      var poi = new BMap.Point(112.53, 37.87);
      map.addControl(new BMap.NavigationControl());
      map.enableScrollWheelZoom(poi, 5);

      map.centerAndZoom(poi, 15);
      var ac = new BMap.Autocomplete({ //建立一个自动完成的对象
        input: "suggestId",
        location: map
      });
      var myValue;
      ac.addEventListener("onconfirm", function(e) {
        //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business;
        th.address_detail = myValue;
        self.form.deviceLocation.address = myValue;
        setPlace();
      });

      function setPlace() {
        map.clearOverlays(); //清除地图上所有覆盖物
        function myFun() {
          th.userlocation = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
          map.centerAndZoom(th.userlocation, 18);
          map.addOverlay(new BMap.Marker(th.userlocation)); //添加标注

          self.form.deviceLocation.longitude = th.userlocation.lng;
          self.form.deviceLocation.latitude = th.userlocation.lat;
          console.log(th.userlocation);
        }
        var local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: myFun
        });
        local.search(myValue);

        //测试输出坐标（指的是输入框最后确定地点的经纬度）
        map.addEventListener("click", function(e) {
          //经度
          console.log(th.userlocation.lng);
          //维度
          console.log(th.userlocation.lat);
        });
      }
      // map.addEventListener("mousemove", function (e) {
      //     console.log(e.point)
      // });
      map.addEventListener("click", function(e) {
        map.clearOverlays();
        //    alert(JSON.stringify(e.point))
        let pt = new BMap.Point(e.point.lng, e.point.lat);
        self.form.deviceLocation.longitude = e.point.lng;
        self.form.deviceLocation.latitude = e.point.lat;
        let marker = new BMap.Marker(pt);
        map.addOverlay(marker);
        var geoc = new BMap.Geocoder();
        let addComp, address;
        geoc.getLocation(e.point, function(rs) {
          addComp = rs.addressComponents;

          self.form.deviceLocation.province = addComp.province;
          self.form.deviceLocation.city = addComp.city;
          self.form.deviceLocation.county = addComp.district;
          address =
            addComp.province +
            addComp.city +
            addComp.district +
            addComp.street +
            addComp.streetNumber;
          th.address_detail = address;
          self.form.deviceLocation.address = address;
        });
      });
    },

    deviceSlaveListdel(s) {
      if (this.form.deviceSlaveList.length <= 1) {
        this.$message({
          message: "从机最少为一个",
          type: "warning"
        });
        return false;
      }
      this.form.deviceSlaveList.splice(s, 1);
    },
    deviceSlaveListadd() {
      this.form.deviceSlaveList.push({
        priority: "",
        name: "",
        slaveSn: "",
        deviceDataRecipeId: ""
      });
    },
    getlist() {
      let para = {
        pageNo: 1,
        pageSize: 1000,
        type: 0,
        authType: 0
      };
      device_group_query(para).then(res => {
        this.begCode(res.code, res.message);
        let _this = this;
        this.addLoading = false;
        if (res.code == 0) {
          foo(res.data);
          function foo(n) {
            for (let i in n) {
              if (!n[i]) {
                console.log(i);
                return true;
              }
              console.log(_this.grouplist);
              _this.grouplist.push(n[i]);
              console.log(n[i].name);
              foo(n[i].childrens);
            }
            // return foo(n.childrens);
          }
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
      device_type_query(para).then(res => {
        this.begCode(res.code, res.message);

        this.addLoading = false;
        if (res.code == 0) {
          this.typelist = res.data.list;
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
      device_data_recipe_query(para).then(res => {
        this.begCode(res.code, res.message);

        this.addLoading = false;
        if (res.code == 0) {
          this.recipelist = res.data.list;
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
      device_model_query(para).then(res => {
        this.begCode(res.code, res.message);

        this.addLoading = false;
        if (res.code == 0) {
          this.modellist = res.data.list;
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
      query_device_user(para).then(res => {
        this.begCode(res.code, res.message);

        this.addLoading = false;
        if (res.code == 0) {
          this.userlist = res.data.list;
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.form);
            for (let i in this.form.deviceSlaveList) {
              if (
                !this.form.deviceSlaveList[i].slaveSn ||
                !this.form.deviceSlaveList[i].name ||
                !this.form.deviceSlaveList[i].deviceDataRecipeId
              ) {
                this.addLoading = false;
                this.$message({
                  message: "从机名称和从机编号数据模板必填",
                  type: "warning"
                });
                return false;
              }
            }
            console.log(para)
            device_template_post(para).then(res => {
              this.begCode(res.code, res.message);

              this.addLoading = false;
              if (res.code == 0) {
                //NProgress.done();
                this.$message({
                  message: "添加成功",
                  type: "success"
                });

                this.$router.push({
                  path: "/template/device"
                });
              } else {
                this.$message({
                  message: res.message,
                  type: "warning"
                });
              }
            });
          });
        } else {
          this.$message({
            message: "请把信息填写完整",
            type: "warning"
          });
        }
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(file.type);
      this.imageUrl = res.data.path;
      this.form.devicePictureList[0].path = res.data.path;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isGIF = file.type === "image/gif";
      let tp = false;
      if (isJPG) {
        tp = isJPG;
      } else if (isPNG) {
        tp = isPNG;
      } else if (isGIF) {
        tp = isGIF;
      } else {
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error("上传头像图片只能是 JPG,GIF,PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return tp && isLt2M;
    }
  },
  mounted() {
    this.menubt=localStorage.getItem('menubt');
    this.map();
    this.getlist();
    let para = {
      pageNo: 1,
      pageSize: 9999
    };
    this.listLoading = true;
    //NProgress.start();
    terminal_user_query(para).then(res => {
      this.begCode(res.code);
      this.total = res.data.totalCount;
      this.terminal_list = res.data.list;
      this.listLoading = false;
      //NProgress.done();
    });
    let para1 = {
      name: "industry",
      pageSize: 999,
      pageNo: 1
    };
    device_template_ui_company_query(para).then(res => {
        if(res.code == 0){
            this.templateUIlist = res.data.list;
        }
    });
    dict_query(para1).then(res => {
      this.begCode(res.code, res.message);
      if (res.code == 0) {
        this.addLoading = false;

        this.industrylist = res.data.list;
      }
    });
    order_query(para).then(res => {
      this.begCode(res.code, res.message);
      if (res.code == 0) {
        this.orderlist = res.data.list;
      }
    });
  }
};
</script>
    <style>
.el-form-item .el-form-item {
  margin-bottom: 22px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-form-item__label {
  font-size: 12px;
}

#allmap {
  height: 400px;
}
</style>